<?php

class Admin_Models_Category extends Libs_Model {

    private $cat_id;
    private $name;
    private $parent_id;

    public function setCatId($cat_id) {
        $this->cat_id = $cat_id;
    }

    public function getCatId() {
        return $this->cat_id;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function setParentId($parent_id) {
        $this->parent_id = $parent_id;
    }

    public function getParentId() {
        return $this->parent_id;
    }

    public function __construct() {
        parent::__construct();
    }

    public function setValue($rows, $isKey = true) {
        $cat = new Admin_Models_Category();
        if ($isKey) {
            $cat->setCatId($rows['cat_id']);
        }
        $cat->setName($rows['name']);
        $cat->setParentId($rows['parent_id']);

        return $cat;
    }

    public function getKeyAndValue(Admin_Models_Category $cat, $isKey = false) {
        $data = array();
        if ($isKey) {
            $data['cat_id'] = $cat->getCatId();
        }
        $data['name'] = $cat->getName();
        $data['parent_id'] = $cat->getParentId();

        return $data;
    }

    public function getParentCat() {
        $sql = "select * from tbl_categories where parent_id = 0";
        $result = $this->db->fetchAllO($sql);
        while ($rows = mysql_fetch_assoc($result)) {
            $out[] = $this->setValue($rows);
        }

        return $out;
    }

    public function getChildCat($parent_id) {
        $sql = "select * from tbl_categories where parent_id = $parent_id";
        $result = $this->db->fetchAllO($sql);
        while ($rows = mysql_fetch_assoc($result)) {
            $out[] = $this->setValue($rows);
        }

        return $out;
    }

    public function insertCat(Admin_Models_Category $cat) {
        $this->db->prepareInsert($this->getKeyAndValue($cat));
        $this->db->insert('tbl_categories');
    }

    public function updateCat(Admin_Models_Category $cat, $cat_id) {
        $this->db->prepareUpdate($this->getKeyAndValue($cat));
        $this->db->updateCat('tbl_categories', $cat_id);
    }

    public function deleteCat($cat_id) {
        $sql = "delete from tbl_categories where cat_id = $cat_id";
        $this->db->query($sql);
        $sql = "delete from tbl_categories where parent_id = $cat_id";
        $this->db->query($sql);
        $sql = "delete from tbl_products where cat_id = $cat_id";
        $this->db->query($sql);
    }

}
